import axios from 'axios'
import { Loading, Message } from 'element-ui'

let loading = {}

axios.interceptors.request.use(config => {
  if (!config.loading || config.loading !== false) {
    loading = Loading.service({
      fullscreen: true,
      background: '0,0,0,1'
    })
  }
  return config
})

axios.interceptors.response.use(
  async response => {
    // 统一错误处理
    const config = response.config
    const flag = Object.prototype.hasOwnProperty.call(config, 'loading') && config.loading === false
    if (!flag && loading) {
      loading.close()
    }
    if (response.data.code && response.data.code !== 1) {
      Message.error(response.data.message)
    }
    return response.data
  },
  e => {
    loading.close()
    const { status } = e.response
    if (status === 401) {
      console.log('401')
    } else if (status === 403) {
      console.log('403')
    }
    return Promise.reject(e)
  }
)

export default axios
